<template>
  <div class="app-container">
    <el-row type="flex" class="row-bg btn-row" justify="end">
      <el-button class="filter-item" size="mini" v-if="$store.state.user.user_perms.includes('502')" @click="add" type="primary" icon="el-icon-plus">{{$t('cards.add')}}</el-button>
    </el-row>
    <el-form :inline="true" :model="q" class="demo-form-inline query" label-position="left" >
      <el-form-item :label="$t('cards.merchant')">
        <el-select v-model="q.mch_id" :label="$t('cards.pls_choose')">
          <el-option :label="$t('cards.all')" :value=null></el-option>
          <el-option v-for="mch of MchList" :key="mch.id" :label="mch.name" :value="mch.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input v-model="q.name" :placeholder="$t('cards.bankcard_name')" prefix-icon="el-icon-edit"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="q.account_number" :placeholder="$t('cards.bankcard_no')" prefix-icon="el-icon-edit"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="q.phone" :placeholder="$t('cards.phone')" prefix-icon="el-icon-edit"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="q.account_holder" :placeholder="$t('cards.cardholder_name')" prefix-icon="el-icon-edit"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="q.bank" :placeholder="$t('cards.bank')" prefix-icon="el-icon-edit"></el-input>
      </el-form-item>
      <el-form-item :label="$t('cards.status')">
        <el-select v-model.number="q.status" :placeholder="$t('cards.status')">
          <el-option :label="$t('cards.all')" :value=null></el-option>
          <el-option v-for="(statu, index) of statusArray" :key="index" :label="statu" :value="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('cards.acct_bal')">
        <el-input v-model="balance.$gte" :placeholder="$t('cards.more')" prefix-icon="el-icon-edit"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="balance.$lt" :placeholder="$t('cards.more')" prefix-icon="el-icon-edit"></el-input>
      </el-form-item>
      <el-form-item :label="$t('cards.pay_type')">
        <el-select v-model.number="q.pay_type" :placeholder="$t('cards.select') + $t('cards.pay_type')">
          <el-option v-for="(statu, index) of PayTypeArrays" :key="index" :label="statu" :value="PayType[index]"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query">{{$t('cards.search')}}</el-button>
        <el-button type="danger" @click="reload">{{$t('cards.reset')}}</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="bankcardData.list" v-loading.body="listLoading"  @sort-change="sortlist"  element-loading-text="Loading" stripe border fit highlight-current-row>
      <el-table-column prop="id" label='ID' width="80"></el-table-column>
      <el-table-column prop="name" :label="$t('cards.name')" width="100"></el-table-column>
      <el-table-column prop="mch_id" :label="$t('cards.mch_id')" width="120"></el-table-column>
      <el-table-column prop="account_number" :label="$t('cards.acct_no')"  width="160"></el-table-column>
      <el-table-column prop="account_holder" :label="$t('cards.acct_holder')" min-width="100"></el-table-column>
      <el-table-column prop="pay_type" :label='$t("order.pay_type")' sortable width="120" :formatter="PayTypeChange"></el-table-column>
      <el-table-column prop="bank" :label="$t('cards.bank')" min-width="150"></el-table-column>
      <el-table-column prop="phone" :label="$t('cards.phone')" min-width="150"></el-table-column>
      <el-table-column prop="subbranch" :label="$t('cards.subbranch')" min-width="150"></el-table-column>
      <el-table-column prop="balance" :label="$t('cards.balance')" min-width="100"></el-table-column>
      <el-table-column prop="desc" :label="$t('cards.desc')" min-width="150"></el-table-column>
      <el-table-column prop="online_status" :label='$t("cards.online_status")' min-width="100">
        <template slot-scope="scope">{{onlineStatusArray[scope.row.online_status]}}</template>
      </el-table-column>
      <el-table-column prop="status" :label="$t('cards.status')" width="100">
        <template slot-scope="scope">{{getStatus(scope.row.status)}}</template>
      </el-table-column>
      <el-table-column prop="updated_at" :label="$t('cards.updated_at')" sortable width="180"></el-table-column>
      <el-table-column prop="created_at" :label="$t('cards.created_at')" width="180"></el-table-column>
      <el-table-column :label="$t('cards.operation')" width="220" fixed="right">
        <template slot-scope="scope">
          <div>
            <el-button type="text" size="small" v-if="roles > 4 && $store.state.user.user_perms.includes('503')" @click="update(scope.row)">[{{$t('cards.edit')}}]</el-button>
            <el-button type="text" size="small" v-if="roles > 4 && $store.state.user.user_perms.includes('504')" @click="remove(scope.row)">[{{$t('cards.delete')}}]</el-button>
             <el-button type="text" size="small" v-if="roles > 4 && $store.state.user.user_perms.includes('506')" @click="viewhistory(scope.row.id, scope.row.name)">[{{$t('cards.history')}}]</el-button>
            <el-button type="text" size="small" v-if="roles > 4 && $store.state.user.user_perms.includes('507')" @click="qrcode(scope.row)">[{{$t('cards.qrcode')}}]</el-button>
            <el-button type="text" size="small" v-if="roles > 4 && $store.state.user.user_perms.includes('505')" @click="stats(scope.row.name)">[{{$t('cards.stats')}}]</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination  @size-change="handleSizeChange" @current-change="handleCurrentChange"
                      :current-page="q.$page" :page-sizes="$store.state.app.pageSizeArr"
                      :page-size="q.$size"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="bankcardData.total_count">
      </el-pagination>
    </div>
    <save-bankcard v-if="showBankcardInfo" :showBankcardInfo.sync ="showBankcardInfo" :bankcard_id="bankcard_id"
                   :MchList="MchList" :bankcard_type="bankcard_type" :PayTypeArray="PayTypeArrays" :PayType="PayType"></save-bankcard>
    <view-statistics v-if="showStatistics" :showStatistics.sync ="showStatistics" :cardCode="cardCode" :cardStatsList="cardStatsList"></view-statistics>
    <view-login-history v-if="showLoginHistory" :showLoginHistory.sync ="showLoginHistory" :cardId="cardId" :cardhistory="cardhistory" :cardName="cardName"></view-login-history>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import saveBankcard from './saveBankcard'
import viewStatistics from './viewStatistics'
import { getBankcardList, deleteBankcard, getBankcardRechargeUrl, getMchList } from '@/api/merchant'
import viewLoginHistory from './viewLoginHistory'

export default {
  components: { saveBankcard, viewStatistics, viewLoginHistory },
  data() {
    return {
      bankcardData: {},
      q: {$size: 30, $page: 1, type: 0},
      listLoading: true,
      showBankcardInfo: false,
      showStatistics: false,
      showLoginHistory: false,
      bankcard_type: 0,
      MchList: [],
      cardStatsList: [],
      balance: {},
      statusArray: [this.$t('cards.inactive'), this.$t('cards.active')],
      onlineStatusArray: [this.$t('cards.offline'), this.$t('cards.online')],
      PayType: ['qr_alipay', 'link_alipay', 'cloud_flash', 'scan_code'],
      bankcard_id: null,
      cardCode: null,
      cardId: null,
      cardhistory: [],
      cardName: null
    }
  },
  computed: {
    ...mapGetters([
      'roles'
    ]),
    PayTypeArrays: function() {
      return [this.$t('cards.qr_alipay'),
        this.$t('cards.link_alipay'),
        this.$t('cards.cloud_flash'),
        this.$t('cards.scan_code')]
    }
  },
  filters: {},
  created() {
    this.getList()
    this.getMchList()
  },
  deactivated(){
    this.listLoading = false
  },
  methods: {
    viewhistory(id, name){
        this.showLoginHistory = true
        this.cardId = id
        this.cardName = name
    },
    getStatus(status){
      return status === 0 ? this.$t('cards.inactive') : this.$t('cards.active')
    },
    sortlist(sort){
      this.q.$orderby = sort.prop
      this.getList()
    },
    add(){
      this.bankcard_id = null
      this.showBankcardInfo = true
    },
    update(row){
      this.bankcard_id = row.id
      this.showBankcardInfo = true
    },
    query(){
      this.getList()
    },
    reload() {
      this.q = {$size: 30, $page: 1, type: 0}
      this.balance = {}
      this.getList()
    },
    PayTypeChange(row) {
      if(row.pay_type === 'qr_alipay') {
        return this.$t('cards.qr_alipay')
      } else if(row.pay_type === 'link_alipay') {
        return this.$t('cards.link_alipay')
      } else if(row.pay_type === 'cloud_flash') {
        return this.$t('cards.cloud_flash')
      } else if(row.pay_type === 'scan_code') {
        return this.$t('cards.scan_code')
      } else {
        return this.$t('cards.unknow')
      }
    },
    remove(row){
      this.$confirm(this.$t('cards.delete_verify') + ` ${row.id} ？`, this.$t('cards.merchant'), {
       confirmButtonText: this.$t('cards.confirm'),
        cancelButtonText: this.$t('cards.cancel'),
        type: 'warning'
      }).then(() => {
        deleteBankcard(row.id).then(res => {
          if(res.status === 0){
            this.$message({ type: 'success', message: this.$t('cards.success_delete') })
            this.getList()
          }
        })
      }).catch(() => {
      })
    },
    qrcode(row){
      this.$prompt(this.$t('cards.qrcode_notif'), '', {
        confirmButtonText: this.$t('cards.confirm'),
        cancelButtonText: this.$t('cards.cancel')
      }).then(({ value }) => {
        let body = {}
        body.id = row.id
        body.amount = value
        getBankcardRechargeUrl(body).then(res => {
          if(res.status === 0){
            this.$message.success(res.data.url)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('cards.cancel_input')
        })
      })
    },
    stats(data){
      this.cardCode = data
      this.showStatistics = true
    },
    handleSizeChange (val) {
      this.q.$size = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.q.$page = val
      this.getList()
    },
    getList() {
      if(this.balance.$gte || this.balance.$lt){
        this.q.balance = this.balance
      }
      let params = Object.assign({
        $orderby: '-updated_at',
        type: 0
      }, this.q)
      this.listLoading = true
      getBankcardList(params).then(res => {
        if (res.status === 0) {
          this.listLoading = false
          this.bankcardData = res.data
        }
      })
    },
    getMchList(){
      getMchList({$size: -1}).then(res => {
        if (res.status === 0) {
          this.MchList = res.data.list
        }
      })
    }
  },
  watch: {
    showBankcardInfo() {
      if(!this.showBankcardInfo){
        this.getList()
      }
    }
  }
}

export const enCards = {
  add: 'Add',
  merchant: 'Company',
  pls_choose: 'Please Choose',
  all: 'All',
  bankcard_name: 'Bankcard name',
  bankcard_no: 'Account No.',
  phone: 'Phone',
  cardholder_name: "Cardholder's name",
  bank: 'Bank',
  online_status: 'Online Status',
  status: 'Status',
  acct_bal: 'Account Balance',
  balance: 'Balance',
  more: 'More than',
  less: 'Less than',
  search: 'Search',
  reset: 'Reset',
  id: 'ID',
  name: 'Card Code',
  mch_id: 'Company ID',
  acct_no: 'Account No.',
  acct_holder: 'Username',
  subbranch: 'Sub branch',
  desc: 'Description',
  updated_at: 'UpdatedAt',
  created_at: 'CreatedAt',
  operation: 'Action',
  edit: 'Edit',
  delete: 'Delete',
  qrcode: 'QR Code',
  stats: 'Statistics',
  active: 'Active',
  inactive: 'Inactive',
  online: 'Online',
  offline: 'Offline',
  cancle_input: 'Cancel Input',
  cancel: 'Cancel',
  confirm: 'Confirm',
  qrcode_notif: 'QR code amount, you can also specify the amount',
  success_delete: 'Successfully deleted',
  delete_verify: 'Are you sure you want to delete the item with the ID of',
  edit_bankcard_info: 'Edit',
  business_info: 'Company',
  weight: 'Weights',
  recharge_limit: 'Recharge Limit',
  login_acct_name: 'Login account name',
  password: 'Login Password',
  payment_password: 'Payment password',
  u_password: 'Ukey password',
  u_expiration: 'Ukey expiration date',
  pls_choose_time: 'Please choose time',
  save: 'Save',
  success_add: 'Added successfully',
  success_edit: 'Successfully modified',
  total_amount: 'Total Amount',
  collection_amount: 'Collection Amount',
  payment_amount: 'Payment Amount',
  manual_close_amount: 'Manual Close Amount',
  auto_close_amount: 'Auto Close Amount',
  processing_amount: 'Processing Amount',
  invalid_amount: 'Invalid Amount',
  total_count: 'Applictaion Count',
  collection_count: 'Collection Count',
  payment_count: 'Payment Count',
  manual_close_count: 'Manual Close Count',
  auto_close_count: 'Auto Close Count',
  processing_count: 'Processing Count',
  invalid_count: 'Invalid Count',
  daily_stats: 'Daily Statistics',
  weekly_stats: 'Weekly Statistics',
  monthly_stats: 'Monthly Statistics',
  close: 'Close',
  card_stats: 'Card Statistics',
  min_auto_close: 'Min auto close order',
  max_auto_close: 'Max auto close order',
  opening_time: 'Opening Time (Hour)',
  closing_time: 'Closing Time (Hour)',
  history: 'History',
  min_balance_limit: 'Min Balance Limit',
  max_balance_limit: 'Max Balance Limit',
  max_cash_flow: 'Max Cash Flow By Day',
  enter_bankcard_name: 'Please enter Bankcard name',
  select: 'Please choose ',
  // Pay Type
  qr_alipay: 'qr_alipay',
  link_alipay: 'link_alipay',
  cloud_flash: 'cloud_flash',
  scan_code: 'scan_code',
  unknow: 'Unknow',
  pay_type: 'Pay type'
}

export const zhCards = {
  add: '新增银行卡',
  merchant: '商户',
  pls_choose: '请选择',
  all: '所有',
  bankcard_name: '银行卡名称',
  bankcard_no: '银行卡号',
  phone: '电话',
  cardholder_name: '持卡人姓名',
  bank: '银行',
  online_status: '在线状态',
  status: '状态',
  acct_bal: '账户金额',
  balance: '余额',
  more: '大于',
  less: '小于',
  search: '查询',
  reset: '重置',
  id: 'ID',
  name: '名称',
  mch_id: '商户号',
  acct_no: '银行卡号',
  acct_holder: '持卡人姓名',
  subbranch: '支行信息',
  desc: '描述',
  updated_at: '更新时间',
  created_at: '创建时间',
  operation: '操作',
  edit: '编辑',
  delete: '删除',
  qrcode: '生成收款码',
  stats: '统计',
  active: '启用',
  inactive: '禁用',
  online: '开启',
  offline: '关闭',
  cancle_input: '取消输入',
  cancel: '取消',
  confirm: '确认',
  qrcode_notif: '二维码金额，也可以不指定金额',
  success_delete: '删除成功',
  delete_verify: '确认删除ID为',
  edit_bankcard_info: '修改银行卡信息',
  business_info: '公司',
  weight: '权重',
  recharge_limit: '告警限额',
  login_acct_name: '登陆账户名',
  password: '登陆密码',
  payment_password: '支付密码',
  u_password: 'U盾密码',
  u_expiration: 'U盾到期时间',
  pls_choose_time: '请选择时间',
  save: '确定',
  success_add: '新增成功',
  success_edit: '修改成功',
  total_amount: '总金额',
  collection_amount: '收款金额',
  payment_amount: '付款金额',
  manual_close_amount: '手工关闭金额',
  auto_close_amount: '自动关闭金额',
  processing_amount: '处理金额',
  invalid_amount: '无效金额',
  total_count: '申请笔数',
  collection_count: '收集计数',
  payment_count: '付款计数',
  manual_close_count: '手动关闭计数',
  auto_close_count: '自动关闭计数',
  processing_count: '处理计数',
  invalid_count: '计数无效',
  daily_stats: '每日统计',
  weekly_stats: '每周统计',
  monthly_stats: '每月统计',
  close: '关',
  card_stats: '卡统计',
  min_auto_close: '最低自动关闭订单',
  max_auto_close: '最大自动关闭订单',
  opening_time: '营业时间(小时)',
  closing_time: '关闭时间(小时)',
  history: '记录',
  min_balance_limit: '最低余额限制',
  max_balance_limit: '最大余额限制',
  max_cash_flow: '每日最大流水',
  enter_bankcard_name: '请输入卡的名称',
  select: '请选择',
  // Pay Type
  qr_alipay: '宝到卡',
  link_alipay: '链接付',
  cloud_flash: '云闪付',
  scan_code: '扫码付',
  unknow: '未知',
  pay_type: '支付方式'
}
</script>
<style>
  .btn-row{
    padding: 0 0 1rem 0;
  }
</style>
